package com.qishon.pc.domain.service;

import com.qishon.pc.domain.model.ProgressControl;
import com.qishon.pc.domain.model.ProgressSteps;
import com.qishon.pc.domain.repository.ProgressControlRepository;
import com.qishon.pc.domain.repository.ProgressStepsRepository;
import com.qishon.pc.domain.util.GirardEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xm on 2016/12/23.
 */
@Slf4j
@Service
public class ProgressStepsService {

    //获取渲染文件路径
    @Value("${run.path}")
    private String filePath;

    @Value("${image.TypeNum}")
    private String jointTimes;
    @Autowired
    ProgressStepsRepository stepsRepository;

    private int sumAllFiles;
    public static int count = 0;
    private int jointFiles;
    @Autowired
    ProgressControlRepository controlRepository;

    public List<ProgressSteps> findByGirardId(ProgressControl progressControl) {
        Map<String, Object> params = new HashMap<>();
        params.put("girardId", progressControl.getId());
        return stepsRepository.findByGirardId(params);
    }

    public void updateCompletedFiles(ProgressSteps progressSteps) {
        stepsRepository.updateCompletedFiles(progressSteps);
    }

    public ProgressSteps findByGirardIdAndStepName(int girardId, String stepName) {
        ProgressSteps progressSteps = new ProgressSteps();
        progressSteps.setGirardId(girardId);
        progressSteps.setStepName(stepName);
        return stepsRepository.findByGirardIdAndStepName(progressSteps);
    }

    public int countAllFiles(int girardId) {
        return stepsRepository.countAllFiles(girardId);
    }

    public int countCompletedFilesFiles(int girardId) {
        return stepsRepository.countCompletedFilesFiles(girardId);
    }

    /**
     * 添加步骤记录
     *
     * @param stepKey         步骤枚举key
     * @param progressControl 所属款号
     * @return progressSteps
     */
    public ProgressSteps addProCtrlSteps(int stepKey, ProgressControl progressControl) {

        GirardEnum girardEnum = GirardEnum.findByKey(stepKey);
        ProgressSteps progressSteps = new ProgressSteps();
        progressSteps.setGirardId(progressControl.getId());
        progressSteps.setStepNo(girardEnum.getFilePtah());
        progressSteps.setStepName(girardEnum.getFileName());
        if (stepKey == 1) {
            List<Integer> files = getAllFiles(stepKey, progressControl);
            sumAllFiles = files.get(0) * files.get(1);
            jointFiles = files.get(0);
            progressSteps.setCompletedFiles(sumAllFiles);
        } else {
            progressSteps.setCompletedFiles(0);
        }
        if (girardEnum.getFilePtah().toUpperCase().equals("01.MODEL")) {
            progressSteps.setCompletedFiles(this.getCompressFiles(progressSteps));
        }
        if (girardEnum.getFilePtah().toUpperCase().equals("02.RENDER")) {
            progressSteps.setAllFiles(sumAllFiles);
        } else if (girardEnum.getFilePtah().toUpperCase().equals("01.MODEL")) {
            progressSteps.setAllFiles(this.getCompressFiles(progressSteps));
        } else if (girardEnum.getFilePtah().toUpperCase().equals("03.CUTOUT")) {
            progressSteps.setAllFiles(sumAllFiles + jointFiles);
        } else if (girardEnum.getFilePtah().toUpperCase().equals("08.DONE")){
            progressSteps.setStepNo("01.Model");
            int all = this.getCompressFiles(progressSteps);
            progressSteps.setAllFiles(all+2);
            progressSteps.setStepNo(girardEnum.getFilePtah());
        }else {
            int _jointTimes = Integer.parseInt(jointTimes)+1;
            progressSteps.setAllFiles(jointFiles*_jointTimes);
        }
        stepsRepository.addProCtrlSteps(progressSteps);
        return progressSteps;
    }

    /**
     * 获取总文件数
     *
     * @param progressControl
     * @return
     */
    public List<Integer> getAllFiles(int setpKey, ProgressControl progressControl) {
        List<Integer> fileList = new ArrayList<>();
        String fileName = "";
        String _filePath = filePath + "\\" + GirardEnum.findByKey(setpKey).getFilePtah() + "\\" + progressControl.getGirard();
        try {
            File file = new File(_filePath);
            if (!file.exists()) {
                return null;
            }
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().indexOf("_02.csv") != -1) {
                    fileName = files[i].getName();
                    break;
                }
            }
            log.info("fileName=" + fileName);
            if (fileName.equals("")) {
                log.info("fileName:GetAllFiles Files not found!");
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(_filePath + "\\" + fileName)));
            String line;
            int num = 0;
            String row = "";
            while ((line = br.readLine()) != null) {
                log.info("csv content:" + line);
                String[] colunm = line.split(",");
                for (int i = 0; i < colunm.length; i++) {
                    if (colunm[i].equals("帧数")) {
                        num = i;
                        break;
                    }
                }
                row += line.split(",")[num].toString() + ",";
            }
            row = row.substring(0, row.length() - 1);
            row = row.replaceAll("帧数,", "");
            String[] alls = row.split(",");
            fileList.add(alls.length);
            fileList.add(Integer.parseInt(alls[0]));
            br.close();
            return fileList;
        } catch (Exception e) {
            log.info("csv:GetAllFiles Files not found!");
            return null;
        }
    }

    /**
     * 获取每一步骤已完成的文件数量
     *
     * @param progressSteps
     * @return Integer
     */
    public int getCompressFiles(ProgressSteps progressSteps) {
        int sumFiles = 0;
        //获取款号
        ProgressControl progressControl = controlRepository.findById(progressSteps.getGirardId());
        //获取当前步骤文件路径: D:\\CloudRender\\步骤编码\\款号\\xx_Color文件夹\\图片文件
        String curPath = filePath + "\\" + progressSteps.getStepNo() + "\\" + progressControl.getGirard();
        //渲染步骤扫描_COLOR文件夹，其他步骤扫描SHADOW和PART
        try {
//            if (progressSteps.getStepNo().toUpperCase().equals("08.DONE")) {
//                File lastFile = new File(curPath);
//                if (!lastFile.exists()) {
//                    return 0;
//                }
//                File[] lastFiles = lastFile.listFiles();
//                for (int x = 0; x < lastFiles.length; x++) {
//                    if (!lastFiles[x].getName().equals("Thumbs.db")) {
//                        sumFiles++;
//                    }
//                }
//            } else
            if (progressSteps.getStepNo().toUpperCase().equals("02.RENDER")) {
                File file = new File(curPath);
                if (!file.exists()) {
                    return 0;
                }
                File[] files = file.listFiles();
                for (int k = 0; k < files.length; k++) {
                    if (files[k].getName().toUpperCase().indexOf("_COLOR") > -1) {
                        File renderFile = new File(curPath + "\\" + files[k].getName());
                        for (File f : renderFile.listFiles()) {
                            if (!f.getName().equals("Thumbs.db")) {
                                sumFiles++;
                            }
                        }
                    }
                }
            } else {
                sumFiles = this.files(curPath);
            }
            return sumFiles;
        } catch (Exception e) {
            log.info("GetCompressFiles Files not found!");
            return -1;
        }
    }

    public ProgressSteps findById(int id) {
        return stepsRepository.findById(id);
    }

    /**
     * 遍历文件数量
     *
     * @param filePath 文件路径
     * @return
     */
    public int files(String filePath) {
        count = 0;
        this.getFile(filePath);
        log.info(filePath + ": all files: " + count);
        return count;
    }

    public static void getFile(String filepath) {
        File file = new File(filepath);
        File[] listfile = file.listFiles();
        if (listfile != null) {
            for (int i = 0; i < listfile.length; i++) {
                if (!listfile[i].isDirectory()) {
                    String temp = listfile[i].toString().substring(7, listfile[i].toString().length());
                    if (temp.indexOf("Thumbs.db") == -1) {
                        log.info("temp==" + temp);
                        count++;
                        log.info("file" + count + "---path=" + listfile[i]);
                    }
                } else {
                    getFile(listfile[i].toString());
                }
            }
        }
    }

    /**
     * 文件拷贝
     *
     * @param src 目标文件地址
     * @param des 目的文件地址
     */
    public boolean copy(String src, String des,boolean overlay) {
        File srcFile = new File(src);

        // 判断源文件是否存在
        if (!srcFile.exists()) {
            log.info("Source File：" + src + "Not Found！");
            return false;
        } else if (!srcFile.isFile()) {
            log.info("Copy File Failed，Source File：" + src + "was not a file ！");
            return false;
        }

        // 判断目标文件是否存在
        File destFile = new File(des);
        if (destFile.exists()) {
            // 如果目标文件存在并允许覆盖
            if (overlay) {
                // 删除已经存在的目标文件，无论目标文件是目录还是单个文件
                new File(des).delete();
            }
        } else {
            // 如果目标文件所在目录不存在，则创建目录
            if (!destFile.getParentFile().exists()) {
                // 目标文件所在目录不存在
                if (!destFile.getParentFile().mkdirs()) {
                    // 复制文件失败：创建目标文件所在目录失败
                    return false;
                }
            }
        }
        // 复制文件
        int byteread = 0; // 读取的字节数
        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];

            while ((byteread = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
            return true;
        } catch (FileNotFoundException e) {
            return false;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void clearFiles(String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                deleteFiles(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deleteFiles(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFiles(files[i]);
            }
        }
        file.delete();
    }
    /**
     * 复制整个目录的内容
     *
     * @param srcDirName
     *            待复制目录的目录名
     * @param destDirName
     *            目标目录名
     * @param overlay
     *            如果目标目录存在，是否覆盖
     * @return 如果复制成功返回true，否则返回false
     */
    public boolean copyDirectory(String srcDirName, String destDirName,
                                        boolean overlay) {
        // 判断源目录是否存在
        File srcDir = new File(srcDirName);
        if (!srcDir.exists()) {
            log.info( "Copy directory failed：Source directory" + srcDirName + "not found！");
            return false;
        } else if (!srcDir.isDirectory()) {
            log.info("Copy directory failed：" + srcDirName + "not a directory ！");
            return false;
        }

        // 如果目标目录名不是以文件分隔符结尾，则加上文件分隔符
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        File destDir = new File(destDirName);
        // 如果目标文件夹存在
        if (destDir.exists()) {
            // 如果允许覆盖则删除已存在的目标目录
            if (overlay) {
                new File(destDirName).delete();
            } else {
                log.info("Copy directory failed：destination directory" + destDirName + "has already exit！");
                return false;
            }
        } else {
            // 创建目的目录
            log.info("destination directory not exit，ready to create ...");
            if (!destDir.mkdirs()) {
                log.info("Copy directory failed：create destination directory failed！");
                return false;
            }
        }

        boolean flag = true;
        File[] files = srcDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 复制文件
            if (files[i].isFile()) {
                flag = this.copy(files[i].getAbsolutePath(),
                        destDirName + files[i].getName(), overlay);
                if (!flag)
                    break;
            } else if (files[i].isDirectory()) {
                flag = this.copyDirectory(files[i].getAbsolutePath(),
                        destDirName + files[i].getName(), overlay);
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            log.info( "Copy directory " + srcDirName + " to " + destDirName + " failed！");
            return false;
        } else {
            return true;
        }
    }
}